import 'dart:ui';
import 'dart:async';
import 'package:LifeMusic/model/musicPlayingListModel.dart';
import 'package:LifeMusic/routers/application.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:LifeMusic/api/songListApi.dart';

import 'package:LifeMusic/model/musicInfoModel.dart';
import 'package:flutter/widgets.dart';
import 'package:like_button/like_button.dart';
import 'package:provider/provider.dart';
import 'package:LifeMusic/provider/musicPlayingProvider.dart';
import 'package:audioplayers/audioplayers.dart';

import 'package:flutter/painting.dart';
import 'package:flutter_vant_kit/widgets/loading.dart';

import 'package:LifeMusic/components/maqueeText.dart';
import 'subtitle.dart';
import 'subtitle_entry.dart';

//https://dengxiaolong.com/article/2019/07/how-to-play-audioplaxyers-in-flutter.html
class SongPlayPage extends StatefulWidget {
  final String musicId;
  const SongPlayPage({Key key, this.musicId}) : super(key: key);
  @override
  _SongPlayPageState createState() => _SongPlayPageState();
}

class _SongPlayPageState extends State<SongPlayPage>
    with TickerProviderStateMixin {
  String musicSrc;
  MusicInfoModel musicInfo = MusicInfoModel();
  bool hasPlay = false;
  bool showLyric = true;
  String stateNowTime = '';
  List<SubtitleEntry> _subtitleList = [];
  PlayerMode mode;
  AudioPlayer audioPlayer = AudioPlayer();
  AnimationController controller;
  Animation animation;
  Duration _duration;
  Duration _position;
  StreamSubscription _durationSubscription;
  StreamSubscription _positionSubscription;
  StreamSubscription _playerCompleteSubscription;
  StreamSubscription _playerErrorSubscription;
  StreamSubscription _playerStateSubscription;
  get _durationText => _duration?.toString()?.split('.')?.first ?? '';
  get _positionText => _position?.toString()?.split('.')?.first ?? '';
  var songLyc = '';
  Timer _countdownTimer;
  int _countdownNum = 3000000;
  Duration start = new Duration(seconds: 0);

  void play(val) async {
    int result = await audioPlayer.play(val);
    if (result == 1) {
      setState(() {
        hasPlay = true;
      });
      print('开始播放');
    } else {
      print('play failed');
    }
  }

  void pause() async {
    final result = await audioPlayer.pause();
    if (result == 1) {
      print('succes');
    }
  }

  //停止播放
  void stop() async {
    final result = await audioPlayer.stop();
    if (result == 1) {
      setState(() {
        _position = Duration();
      });
    }
  }

  Future getMusic(id) async {
    var result = await SongApi.getMusicUrl(id);
    return result;
  }

  Future getLyric(id) async {
    var result = await SongApi.Lyric(id);
    return result;
  }

  Future getMusicInfo(id) {
    return SongApi.getMusicDetail(id);
  }

  _initAudioPlayer() {
    //  /// Ideal for long media files or streams.
    mode = PlayerMode.MEDIA_PLAYER;
    //初始化
    audioPlayer = AudioPlayer(mode: mode);

    _durationSubscription = audioPlayer.onDurationChanged.listen((duration) {
      setState(() => _duration = duration);

      // TODO implemented for iOS, waiting for android impl
      if (Theme.of(context).platform == TargetPlatform.iOS) {
        // (Optional) listen for notification updates in the background
        audioPlayer.startHeadlessService();

        // set at least title to see the notification bar on iOS.
        audioPlayer.setNotification(
            title: 'App Name',
            artist: 'Artist or blank',
            albumTitle: 'Name or blank',
            imageUrl: 'url or blank',
            forwardSkipInterval: const Duration(seconds: 30), // default is 30s
            backwardSkipInterval: const Duration(seconds: 30), // default is 30s
            duration: duration,
            elapsedTime: Duration(seconds: 0));
      }
    });

    //监听进度
    _positionSubscription =
        audioPlayer.onAudioPositionChanged.listen((p) => setState(() {
              _position = p;
            }));

    //播放完成
    _playerCompleteSubscription =
        audioPlayer.onPlayerCompletion.listen((event) {
//          _onComplete();
      setState(() {
        _position = Duration();
      });
    });

    //监听报错
    _playerErrorSubscription = audioPlayer.onPlayerError.listen((msg) {
      print('audioPlayer error : $msg');
      setState(() {
//        _playerState = PlayerState.stopped;
        _duration = Duration(seconds: 0);
        _position = Duration(seconds: 0);
      });
    });

    //播放状态改变
    audioPlayer.onPlayerStateChanged.listen((state) {
      // print(state);
      var provider = Provider.of<PlayingStatus>(context, listen: false);
      print(state.toString() == 'AudioPlayerState.PLAYING');
      state.toString() == 'AudioPlayerState.PLAYING'
          ? provider.hasPlaying = true
          : provider.hasPlaying = false;
      provider.hasPlayingSongs = musicInfo;
      if (!mounted) return;
      setState(() {});
    });

    ///// iOS中来自通知区域的玩家状态变化流。
    audioPlayer.onNotificationPlayerStateChanged.listen((state) {
      if (!mounted) return;
    });

//    _playingRouteState = PlayingRouteState.speakers;
  }

  void _play() async {
    final playPosition = (_position != null &&
            _duration != null &&
            _position.inMilliseconds > 0 &&
            _position.inMilliseconds < _duration.inMilliseconds)
        ? _position
        : null;
    final result = await audioPlayer.play(musicSrc, position: playPosition);
    if (result == 1) {
      setState(() {
        hasPlay = true;
      });
    }
    audioPlayer.setPlaybackRate(playbackRate: 1.0);
  }

  loadData() {
    RegExp exp1 = new RegExp(r'(?<=\[).*?(?=\.)');
    var list = songLyc.split(RegExp('\n'));
    list.forEach((f) {
      if (f.isNotEmpty) {
        var time = exp1.stringMatch(f);
        var r = f.split(RegExp((r'\[.*?\]')));
        _subtitleList.add(SubtitleEntry(time, r[1]));
      }
    });
  }

  void musicChange(musicId) {
    getMusicInfo(musicId).then((value) {
      setState(() {
        musicInfo = MusicInfoModel.fromJson(value);
      });
    });
    getMusic(musicId).then((value) {
      print(value["data"]);
      setState(() {
        musicSrc = value["data"][0]["url"];
      });
      getLyric(musicId).then((value) {
        setState(() {
          songLyc = value["lrc"]["lyric"];
        });
        loadData();
        _play();
        MusicInfoModel music =
            Provider.of<PlayingStatus>(context, listen: false).hasPlayingSongs =
                musicInfo;
      });
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initAudioPlayer(); // 初始化音乐播放器
    controller = AnimationController(
        duration: const Duration(milliseconds: 15000), vsync: this);
    animation = new CurvedAnimation(parent: controller, curve: Curves.linear);
    //动画开始、结束、向前移动或向后移动时会调用StatusListener
    controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        controller.repeat();
      } else if (status == AnimationStatus.dismissed) {
        controller.forward();
      }
    });
    controller.forward();
    audioPlayer.onAudioPositionChanged.listen((p) async {
      String inMinutes = p.inMinutes.toString().padLeft(2, '0');
      String inSeconds = (p.inSeconds % 60).toString().padLeft(2, '0');
      setState(() {
        stateNowTime = inMinutes + ':' + inSeconds;
        // print('$stateNowTime');
      });
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      musicChange(widget.musicId);
    });
  }

  @override
  void deactivate() async {
    print('结束');
    int result = await audioPlayer.release();
    if (result == 1) {
      print('release success');
    } else {
      print('release failed');
    }
    super.deactivate();
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return musicInfo?.songs == null
        ? Center(
            child: Loading(
              color: Colors.blueAccent,
              text: '正在努力加载中...',
            ),
          )
        : Consumer<PlayingStatus>(builder: (context, playingMusic, child) {
            return Stack(
              children: [
                backGroundContainer(
                    imgUrl: 'assets/wallpaper/sunset-mountains-0.jpg'),
                backGroundFilter(
                  blurX: 3.0,
                  blurY: 5.0,
                  opacity: 0.6,
                ),
                opacityAppBar(musicInfo),
                showLyric
                    ? Positioned(
                        top: MediaQuery.of(context).size.height / 5,
                        right: 0,
                        left: 0,
                        child: Center(
                          child: RotationTransition(
                            alignment: Alignment.center,
                            turns: animation,
                            child: InkWell(
                              onTap: () {
                                setState(() {
                                  showLyric = false;
                                });
                              },
                              child: Container(
                                width: 260,
                                height: 260,
                                decoration: BoxDecoration(
                                    image: new DecorationImage(
                                        image: new ExactAssetImage(
                                            'assets/images/timg.jpg'),
                                        fit: BoxFit.cover),
                                    borderRadius: BorderRadius.circular(130)),
                                child: Center(
                                  child: Container(
                                    margin: EdgeInsets.all(50),
                                    child: CircleAvatar(
                                      radius: 100,
                                      backgroundImage: NetworkImage(
                                          musicInfo?.songs[0]?.al?.picUrl),
                                      child: Container(
                                        alignment: Alignment(0, .5),
                                        width: 200,
                                        height: 200,
                                        // child: Text("兵长利威尔")
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      )
                    : InkWell(
                        onTap: () {
                          setState(() {
                            showLyric = true;
                          });
                        },
                        child: Stack(
                          children: <Widget>[
                            _subtitleList.isNotEmpty
                                ? Positioned.fill(
                                    child: Subtitle(
                                    stateNowTime,
                                    _subtitleList,
                                    diameterRatio: 2,
                                    selectedTextStyle: TextStyle(
                                        color: Colors.white, fontSize: 18),
                                    unSelectedTextStyle: TextStyle(
                                      color: Colors.black.withOpacity(.6),
                                    ),
                                    itemExtent: 45,
                                  ))
                                : Column(
                                    children: [
                                      Expanded(
                                          child: Center(
                                        child: Text(
                                          '暂无歌词',
                                          style: TextStyle(
                                              color: Colors.grey, fontSize: 16),
                                        ),
                                      ))
                                    ],
                                  )
                          ],
                        )),
                Container(
                  margin: EdgeInsets.only(bottom: 20),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          LikeButton(
                            likeBuilder: (bool isLiked) {
                              return Icon(
                                Icons.favorite_border_outlined,
                                color: isLiked ? Colors.red : Colors.grey,
                              );
                            },
                            circleColor: CircleColor(
                                start: Colors.pinkAccent, end: Colors.red),
                            bubblesColor: BubblesColor(
                              dotPrimaryColor: Colors.red,
                              dotSecondaryColor: Color(0xff0099cc),
                            ),
                          ),
                          controlButton(Icons.cloud_download_outlined,
                              callback: () {}),
                          controlButton(Icons.high_quality_outlined,
                              callback: () {}),
                          controlButton(Icons.mode_comment_outlined,
                              callback: () {
                            Application.router.navigateTo(
                                context, '/remakeList?musicInfo',
                                transition: TransitionType.fadeIn);
                          }),
                          controlButton(Icons.more_vert_outlined,
                              callback: () {}),
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          timerContainer(
                              _position != null ? _positionText : '0:00:00',
                              left: 20.0),
                          progressBar(),
                          timerContainer(
                              _duration != null ? _durationText : '0:00:00',
                              right: 20.0),
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          controlButton(Icons.sync_alt_outlined,
                              callback: () {}),
                          controlButton(Icons.fast_rewind_outlined,
                              callback: () {
                            if (playingMusic.musicIndex <= 0) return;
                            deactivate();
                            // print(playingMusic.playingList.songs[playingMusic.musicIndex-1].id.toString());
                            musicChange(playingMusic
                                .playingList.songs[playingMusic.musicIndex].id
                                .toString());
                            playingMusic.musicIndex =
                                playingMusic.musicIndex - 1;
                            print(playingMusic.musicIndex);
                          }),
                          controlButton(
                              !hasPlay
                                  ? Icons.play_circle_outline
                                  : Icons.pause_circle_filled_outlined,
                              callback: () {
                            setState(() {
                              hasPlay = !hasPlay;
                            });
                            hasPlay ? _play() : pause();
                          }, size: 50),
                          controlButton(Icons.fast_forward_outlined,
                              callback: () {
                            if (playingMusic.musicIndex >=
                                playingMusic.playingList.songs.length) return;
                            deactivate();
                            musicChange(playingMusic
                                .playingList.songs[playingMusic.musicIndex].id
                                .toString());
                            playingMusic.musicIndex =
                                playingMusic.musicIndex + 1;
                          }),
                          controlButton(Icons.queue_music, callback: () {}),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            );
          });
  }

  Widget timerContainer(String text, {double left = 0.0, double right = 0.0}) {
    return Container(
      margin: EdgeInsets.only(left: left, right: right),
      child: Text(
        text,
        style: TextStyle(color: Colors.white, fontSize: 8),
      ),
    );
  }

  // 背景图
  Widget backGroundContainer({String imgUrl}) {
    return new Container(
      decoration: new BoxDecoration(
        image: new DecorationImage(
          image: new ExactAssetImage(imgUrl),
          fit: BoxFit.cover,
          colorFilter: new ColorFilter.mode(
            Colors.white,
            BlendMode.overlay,
          ),
        ),
      ),
    );
  }

  //背景模糊度
  backGroundFilter({double blurX, double blurY, double opacity}) {
    return Container(
        child: new BackdropFilter(
      filter: ImageFilter.blur(sigmaX: blurX, sigmaY: blurY),
      child: Opacity(
        opacity: opacity,
        child: new Container(
          decoration: new BoxDecoration(
            color: Colors.grey.shade900,
          ),
        ),
      ),
    ));
  }

  //透明appBar
  Widget opacityAppBar(MusicInfoModel music,
      {Color barColor = Colors.grey, IconData icons1, IconData icons2}) {
    return Container(
      child: AppBar(
        iconTheme: IconThemeData(
          color: barColor, //修改颜色
        ),
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            MarqueeWidget(
              direction: Axis.horizontal,
              child: Text(
                music.songs == null ? '' : music.songs[0].name,
                style: TextStyle(color: barColor, fontSize: 16),
              ),
            ),
            Text(
              '${musicInfo.songs[0].ar[0].name}-${musicInfo?.songs[0]?.al?.name}',
              style: TextStyle(color: barColor, fontSize: 12),
            )
          ],
        ),
        actions: [
          Container(
            margin: EdgeInsets.only(right: 10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                controlButton(Icons.favorite_border, iconColor: Colors.red),
                SizedBox(
                  width: 15,
                ),
                controlButton(Icons.share_outlined),
              ],
            ),
          ),
        ],
      ),
    );
  }

  //进度条
  Widget progressBar() {
    return Container(
      height: 100,
      width: MediaQuery.of(context).size.width / 1.5,
      child: SliderTheme(
        data: SliderTheme.of(context).copyWith(
            activeTrackColor: Colors.pink, //进度条滑块左边颜色
            // inactiveTrackColor: Colors.blue, //进度条滑块右边颜色
            // thumbColor: Colors.yellow, //滑块颜色
            // overlayColor: Colors.green, //滑块拖拽时外圈的颜色
            overlayShape: RoundSliderOverlayShape(
              //可继承SliderComponentShape自定义形状
              overlayRadius: 25, //滑块外圈大小
            ),
            thumbShape: RoundSliderThumbShape(
              //可继承SliderComponentShape自定义形状
              disabledThumbRadius: 15, //禁用是滑块大小
              enabledThumbRadius: 10, //滑块大小
            ),
            // inactiveTickMarkColor: Colors.black,
            tickMarkShape: RoundSliderTickMarkShape(
              //继承SliderTickMarkShape可自定义刻度形状
              tickMarkRadius: 1.0, //刻度大小
            ),
            showValueIndicator: ShowValueIndicator.onlyForDiscrete, //气泡显示的形式
            valueIndicatorColor: Colors.red, //气泡颜色
            valueIndicatorShape: PaddleSliderValueIndicatorShape(), //气泡形状
            valueIndicatorTextStyle: TextStyle(color: Colors.black), //气泡里值的风格
            trackHeight: 2 //进度条宽度
            ),
        child: Slider(
          label: '$_positionText',
          // divisions: ,
          onChanged: (v) {
            final Position = v * _duration.inMilliseconds;
            audioPlayer.seek(Duration(milliseconds: Position.round()));
          },
          value: (_position != null &&
                  _duration != null &&
                  _position.inMilliseconds > 0 &&
                  _position.inMilliseconds < _duration.inMilliseconds)
              ? _position.inMilliseconds / _duration.inMilliseconds
              : 0.0,
        ),
      ),
    );
  }

  //底部控制器btn
  Widget controlButton(IconData icons,
      {Color iconColor = Colors.grey, Function callback, double size = 26}) {
    return InkWell(
      onTap: () {
        callback();
      },
      child: Icon(
        icons,
        size: size,
        color: iconColor,
      ),
    );
  }
}
//https://kinsomyjs.github.io/2019/01/08/Flutter%E4%BB%BF%E7%BD%91%E6%98%93%E4%BA%91%E9%9F%B3%E4%B9%90-%E4%B8%80/
// https://blog.csdn.net/zl18603543572/article/details/95317780
